package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 攻略评论服务
 */
@Service
public class TravelCommentServiceImpl implements ITravelCommentService{

    @Autowired
    private TravelCommentRepository strategyCommentRepository; //操作简单的crud

    @Autowired
    private MongoTemplate mongoTemplate; //操作高级查询

    //评论保存操作
    @Override
    public TravelComment save(TravelComment comment) {

        comment.setCreateTime(new Date());

        //需要额外处理评论的评论
        if(comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE){ //如果是评论的评论
            String refId = comment.getRefComment().getId();
            if(StringUtils.hasLength(refId)){
                TravelComment reComment = strategyCommentRepository.findById(refId).get();
                comment.setRefComment(reComment);
            }
        }

        strategyCommentRepository.save(comment);

        return comment;
    }

    //分页查询
    @Override
    public Page query(TravelCommentQuery qo) {

        Query query = new Query();

        //条件
        if(qo.getTravelId() != -1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        //分页条件
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");

        //查总数
        //toatl
        long total = mongoTemplate.count(query, TravelComment.class);

        //设置分页条件
        query.with(pageable);

        //查当前页显示数据集合
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);

        //分页封装对象
        return new PageImpl(list,pageable,total);
    }

    //查询总数
    @Override
    public Long getCount(Long travelId) {

        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));

        long total = mongoTemplate.count(query, TravelComment.class);

        return total;
    }

}
